﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.ComponentModel.Composition;
using System.IO;

namespace TextToHTML
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            Compose();
        }

        private static CompositionContainer _container {get; set;}

        /// <summary>
        /// Get MEF up and going and plug everything together!
        /// </summary>
        /// <returns></returns>
        private bool Compose()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            catalog.Catalogs.Add(new DirectoryCatalog(new FileInfo(Assembly.GetCallingAssembly().Location).DirectoryName));

            UseCatalogDirectory(catalog, new DirectoryInfo(Environment.SpecialFolder.CommonApplicationData + "\\TextToHTML"));
            UseCatalogDirectory(catalog, new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\TextToHTML"));

            _container = new CompositionContainer(catalog);
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(this);

            try
            {
                _container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                Shutdown(1);
                return false;
            }
            return true;
        }

        /// <summary>
        /// Add a directory to the catalog, but only if it exists.
        /// </summary>
        /// <param name="catalog"></param>
        /// <param name="f"></param>
        private static void UseCatalogDirectory(AggregateCatalog catalog, DirectoryInfo f)
        {
            if (f.Exists)
            {
                catalog.Catalogs.Add(new DirectoryCatalog(f.FullName));
            }
        }

        public static void ComposeMe(object obj)
        {
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(obj);
            _container.Compose(batch);
        }
    }
}
